import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

export const useUserManagementStore = defineStore('userManagement', () => {
  // 状态
  const userList = ref([])
  const loading = ref(false)
  const selectedUsers = ref([])
  
  // 分页信息
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })

  // 搜索条件
  const searchForm = reactive({
    username: '',
    nickname: '',
    email: '',
    phone: '',
    status: '',
    roleId: ''
  })

  // 模拟用户数据
  const mockUsers = Array.from({ length: 100 }, (_, i) => ({
    id: `user_${String(i + 1).padStart(3, '0')}`,
    username: `user${i + 1}`,
    nickname: `用户${i + 1}`,
    email: `user${i + 1}@example.com`,
    phone: `138${String(Math.random()).slice(2, 10)}`,
    status: Math.random() > 0.2 ? 1 : 0, // 1: 正常, 0: 禁用
    roleIds: ['role_normal'],
    roles: [{ id: 'role_normal', name: '普通用户' }],
    avatar: '',
    lastLoginTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
    createdAt: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
    updatedAt: new Date().toISOString()
  }))

  // 模拟角色数据
  const mockRoles = [
    { id: 'role_admin', name: '管理员' },
    { id: 'role_editor', name: '编辑员' },
    { id: 'role_normal', name: '普通用户' },
    { id: 'role_viewer', name: '访客' }
  ]

  /**
   * 获取用户列表
   */
  async function fetchUserList() {
    loading.value = true
    try {
      // 模拟 API 调用延迟
      await new Promise(resolve => setTimeout(resolve, 500))

      // 过滤数据
      let filteredUsers = mockUsers.filter(user => {
        if (searchForm.username && !user.username.includes(searchForm.username)) return false
        if (searchForm.nickname && !user.nickname.includes(searchForm.nickname)) return false
        if (searchForm.email && !user.email.includes(searchForm.email)) return false
        if (searchForm.phone && !user.phone.includes(searchForm.phone)) return false
        if (searchForm.status !== '' && user.status !== Number(searchForm.status)) return false
        if (searchForm.roleId && !user.roleIds.includes(searchForm.roleId)) return false
        return true
      })

      // 分页处理
      const start = (pagination.current - 1) * pagination.pageSize
      const end = start + pagination.pageSize
      
      userList.value = filteredUsers.slice(start, end)
      pagination.total = filteredUsers.length

      return { success: true, data: userList.value }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      return { success: false, message: error.message || '获取用户列表失败' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取用户详情
   */
  async function getUserDetail(userId) {
    try {
      const user = mockUsers.find(u => u.id === userId)
      if (!user) {
        throw new Error('用户不存在')
      }
      return { success: true, data: user }
    } catch (error) {
      console.error('获取用户详情失败:', error)
      return { success: false, message: error.message || '获取用户详情失败' }
    }
  }

  /**
   * 创建用户
   */
  async function createUser(userData) {
    try {
      // 模拟 API 调用延迟
      await new Promise(resolve => setTimeout(resolve, 300))

      const newUser = {
        id: `user_${Date.now()}`,
        ...userData,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }

      mockUsers.unshift(newUser)
      
      return { success: true, data: newUser, message: '用户创建成功' }
    } catch (error) {
      console.error('创建用户失败:', error)
      return { success: false, message: error.message || '创建用户失败' }
    }
  }

  /**
   * 更新用户
   */
  async function updateUser(userId, userData) {
    try {
      // 模拟 API 调用延迟
      await new Promise(resolve => setTimeout(resolve, 300))

      const userIndex = mockUsers.findIndex(u => u.id === userId)
      if (userIndex === -1) {
        throw new Error('用户不存在')
      }

      mockUsers[userIndex] = {
        ...mockUsers[userIndex],
        ...userData,
        updatedAt: new Date().toISOString()
      }

      return { success: true, data: mockUsers[userIndex], message: '用户更新成功' }
    } catch (error) {
      console.error('更新用户失败:', error)
      return { success: false, message: error.message || '更新用户失败' }
    }
  }

  /**
   * 删除用户
   */
  async function deleteUser(userId) {
    try {
      // 模拟 API 调用延迟
      await new Promise(resolve => setTimeout(resolve, 300))

      const userIndex = mockUsers.findIndex(u => u.id === userId)
      if (userIndex === -1) {
        throw new Error('用户不存在')
      }

      mockUsers.splice(userIndex, 1)
      
      return { success: true, message: '用户删除成功' }
    } catch (error) {
      console.error('删除用户失败:', error)
      return { success: false, message: error.message || '删除用户失败' }
    }
  }

  /**
   * 批量删除用户
   */
  async function batchDeleteUsers(userIds) {
    try {
      // 模拟 API 调用延迟
      await new Promise(resolve => setTimeout(resolve, 500))

      userIds.forEach(userId => {
        const userIndex = mockUsers.findIndex(u => u.id === userId)
        if (userIndex !== -1) {
          mockUsers.splice(userIndex, 1)
        }
      })

      return { success: true, message: `成功删除 ${userIds.length} 个用户` }
    } catch (error) {
      console.error('批量删除用户失败:', error)
      return { success: false, message: error.message || '批量删除用户失败' }
    }
  }

  /**
   * 更新用户状态
   */
  async function updateUserStatus(userId, status) {
    try {
      // 模拟 API 调用延迟
      await new Promise(resolve => setTimeout(resolve, 300))

      const userIndex = mockUsers.findIndex(u => u.id === userId)
      if (userIndex === -1) {
        throw new Error('用户不存在')
      }

      mockUsers[userIndex].status = status
      mockUsers[userIndex].updatedAt = new Date().toISOString()

      return { success: true, message: '用户状态更新成功' }
    } catch (error) {
      console.error('更新用户状态失败:', error)
      return { success: false, message: error.message || '更新用户状态失败' }
    }
  }

  /**
   * 重置用户密码
   */
  async function resetUserPassword(userId) {
    try {
      // 模拟 API 调用延迟
      await new Promise(resolve => setTimeout(resolve, 300))

      const user = mockUsers.find(u => u.id === userId)
      if (!user) {
        throw new Error('用户不存在')
      }

      // 模拟生成新密码
      const newPassword = Math.random().toString(36).slice(-8)

      return { success: true, data: { newPassword }, message: '密码重置成功' }
    } catch (error) {
      console.error('重置密码失败:', error)
      return { success: false, message: error.message || '重置密码失败' }
    }
  }

  /**
   * 获取角色列表
   */
  async function getRoleList() {
    try {
      return { success: true, data: mockRoles }
    } catch (error) {
      console.error('获取角色列表失败:', error)
      return { success: false, message: error.message || '获取角色列表失败' }
    }
  }

  /**
   * 重置搜索条件
   */
  function resetSearchForm() {
    Object.keys(searchForm).forEach(key => {
      searchForm[key] = ''
    })
  }

  /**
   * 重置分页
   */
  function resetPagination() {
    pagination.current = 1
    pagination.pageSize = 10
    pagination.total = 0
  }

  return {
    // 状态
    userList,
    loading,
    selectedUsers,
    pagination,
    searchForm,
    mockRoles,
    
    // 方法
    fetchUserList,
    getUserDetail,
    createUser,
    updateUser,
    deleteUser,
    batchDeleteUsers,
    updateUserStatus,
    resetUserPassword,
    getRoleList,
    resetSearchForm,
    resetPagination
  }
})
